package cn.ad.server.job.adapter.persistence.job;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import cn.ad.server.persistence.dao.StrategyUserDmpMapDao;
import cn.ad.server.domain.ad.StrategyUserDmpMap;
import cn.ad.server.job.domain.job.StrategyUserDmpMapRepositoryService;

@Repository
public class StrategyUserDmpMapRepositoryServant implements StrategyUserDmpMapRepositoryService {

	static final Logger logger = LoggerFactory.getLogger(StrategyUserDmpMapRepositoryServant.class);

	@Autowired
	private StrategyUserDmpMapDao strategyUserDmpMapDao;

	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, ArrayList<String>> strategyUserDmpOperations;
	
	@Resource(name = "cacheRedisTemplate")
	private RedisTemplate<String, String> cacheRedisTemplate;

	@Override
	public void warmAllStrategyUserDmpMap() {
		ConcurrentHashMap<String, ArrayList<String>> assembleData = getAssembleData();
		Enumeration<String> keys = assembleData.keys();
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			ArrayList<String> value = assembleData.get(key);
			if(value==null||value.isEmpty()){
				cacheRedisTemplate.delete(StrategyUserDmpMap.cacheKey(key));
			}else{
				strategyUserDmpOperations.set(StrategyUserDmpMap.cacheKey(key), value);
			}
		}

//		Set<String> keySet = assembleData.keySet();
//		for (String key : keySet) {
//			ArrayList<String> value = assembleData.get(key);
//			if(value==null||value.isEmpty()){
//				cacheRedisTemplate.delete(StrategyUserDmpMap.cacheKey(key));
//			}else{
//				strategyUserDmpOperations.set(StrategyUserDmpMap.cacheKey(key), value);
//			}
//		}
	}
	
	
	/**
	 * 获得分组后的数据。
	 * @return
	 */
	private ConcurrentHashMap<String, ArrayList<String>> getAssembleData(){
		ConcurrentHashMap<String, ArrayList<String>> maps = new ConcurrentHashMap<>();
		List<StrategyUserDmpMap> strategyUserDmpMaps = strategyUserDmpMapDao.findAll();
		for (StrategyUserDmpMap sud : strategyUserDmpMaps) {
			ArrayList<String> arrayList = maps.get(sud.getCompsiteKey());
			if(arrayList==null){	
				arrayList = new ArrayList<>();
				maps.putIfAbsent(sud.getCompsiteKey(), arrayList);
			}
			if (sud.getStatus()==1) {
				arrayList.add(String.valueOf(sud.getUserDmpId()));
			}else {
				arrayList.remove(String.valueOf(sud.getUserDmpId()));
			}
		}
		return maps;
	}
	
}
